﻿using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Indentation;
using ICSharpCode.AvalonEdit.Rendering;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Media;

namespace DSSDataServiceGenerator.Controls
{
    class CodeEditor
        : TextEditor
    {
        public CodeEditor()
            : base()
        {
            this.Initialize();
        }

        private void Initialize()
        {
            this.IsReadOnly = true;

            this.ShowLineNumbers = false;

            this.CodeLanguage = CodeEditorLanguage.Xml;

            this.Options.AllowScrollBelowDocument = true;

            this.Options.RequireControlModifierForHyperlinkClick = true;

            this.TextArea.IndentationStrategy = new DefaultIndentationStrategy();
        }

        public static readonly DependencyProperty TextProperty = DependencyProperty.Register("Text", typeof(string), typeof(CodeEditor), new FrameworkPropertyMetadata(null, TextProperty_Changed));

        public new string Text
        {
            get { return (string)GetValue(TextProperty); }
            set { SetValue(TextProperty, value); }
        }

        public static void TextProperty_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            TextEditor host = sender as TextEditor;

            if (host != null)

                host.Text = Convert.ToString(e.NewValue);
        }

        private string GetExtension(CodeEditorLanguage language)
        {
            switch (language)
            {
                case CodeEditorLanguage.Xml:
                    return ".xml";
                case CodeEditorLanguage.Csharp:
                    return ".cs";
                default:
                    return string.Empty;
            }
        }

        public CodeEditorLanguage CodeLanguage
        {
            get { return (CodeEditorLanguage)GetValue(CodeLanguageProperty); }
            set { SetValue(CodeLanguageProperty, value); }
        }

        public static readonly DependencyProperty CodeLanguageProperty = DependencyProperty.Register("CodeLanguage", typeof(CodeEditorLanguage), typeof(CodeEditor), new PropertyMetadata(CodeEditorLanguage.Default, LanguageProperty_Changed));

        public static void LanguageProperty_Changed(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            CodeEditor host = sender as CodeEditor;

            if (host != null)

                host.SyntaxHighlighting = HighlightingManager.Instance.GetDefinitionByExtension(host.GetExtension(host.CodeLanguage));
        }
    }
}
